package com.conwax.gmap;

import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebComponent;
import org.apache.wicket.util.string.JavascriptUtils;
import org.apache.wicket.util.value.IValueMap;

import com.conwax.gmap.event.GEventSource;

public class Map2NG extends WebComponent implements GEventSource
{

	private static final long serialVersionUID = 1L;
	private DivElementContainer div;
	private final String target = "window";
	private final String event = "\"domready\"";
	private final int id;
	private GLatLng center;
	private int zoom;

	public Map2NG(String id, DivElementContainer div)
	{
		super(id);
		this.div = div;
		this.div.setOutputMarkupId(true);
		this.id = Session.get().nextSequenceValue();
		this.setOutputMarkupId(true);
	}

	public void setCenter(GLatLng latLng, int i)
	{
		this.center = latLng;
		this.zoom = i;
	}

	/**
	 * @see org.apache.wicket.Component#onComponentTag(org.apache.wicket.markup.ComponentTag)
	 */
	@Override
	protected void onComponentTag(ComponentTag tag)
	{
		// Must be attached to a script tag
		checkComponentTag(tag, "script");
		IValueMap attributes = tag.getAttributes();
		attributes.put("type", "text/javascript");
	}

	/**
	 * @see org.apache.wicket.Component#onComponentTagBody(org.apache.wicket.markup.MarkupStream,
	 *      org.apache.wicket.markup.ComponentTag)
	 */
	@Override
	protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
	{
		replaceComponentTagBody(markupStream, openTag, JavascriptUtils.SCRIPT_CONTENT_PREFIX
				+ getJSInit()
				+ JavascriptUtils.SCRIPT_CONTENT_SUFFIX);
	}

	public String getJSInit()
	{
		String jsInit = "Wicket.Event.add(" + target + ", " + event + ", function(event) { "
				+ "WicketConGoogle.Map2(\"" + id + "\", \"" + div.getMarkupId() + "\");"
				+ "WicketConGoogle.maps[" + id + "].map.setCenter(" + center.getJSInit() + ", "
				+ zoom + ");});";
		return jsInit;
	}

	@Override
	protected void onRemove()
	{
		if (AjaxRequestTarget.get() != null) {
			AjaxRequestTarget.get().appendJavascript("remove the JavaScript objects that belong to me.");
		}
		super.onRemove();
	}
	
}
